package com.ogilvy.cms.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ogilvy.cms.bean.CmsPage;
import com.ogilvy.cms.dao.CmsLeftTreeDao;
import com.ogilvy.cms.service.CmsLeftTreeService;
import com.ogilvy.common.UtilTools;
import com.ogilvy.frame.service.BaseServiceImpl;

@Service
public class CmsLeftTreeServiceImpl extends BaseServiceImpl implements CmsLeftTreeService{

	@Autowired
	protected CmsLeftTreeDao cmsLeftTreeDao;
	
	public String leftTreeJson() {
		List<CmsPage> datalist = cmsLeftTreeDao.getLeftTreeList();
		List<CmsPage> onelist = getChildrenList(datalist, 0);
		
		List<Map> nodelist = new ArrayList<Map>();
		for(int i=0;i<onelist.size();i++){
			CmsPage cp = datalist.get(i);
			Map m = getNodeList(cp, datalist);
			nodelist.add(m);
		}
		return UtilTools.encodeObject2Json(nodelist);
	}
	
	private List<CmsPage> getChildrenList(List<CmsPage> datalist, Integer pid){
		List<CmsPage> rlist = new ArrayList<CmsPage>();
		boolean start = true;
		boolean findstart = false;
		for(int i=0;i<datalist.size();i++){
			CmsPage cp = datalist.get(i);
			if(cp.getParentCmpId().intValue() == pid.intValue()){
				findstart = true;
				rlist.add(cp);
			}else{
				if(findstart && !start){
					break;
				}
				if(findstart){
					start = false;
				}
			}
		}
		return rlist;
	}
	
	private Map getNodeList(CmsPage cp, List<CmsPage> datalist){
		Map m = new HashMap();
		m.put("cmpId", cp.getCmpId());
		m.put("text", cp.getCmpName());
		m.put("url", cp.getCmt().getCmtUrl() + (!cp.getCmt().getCmtUrl().equals("#")&&cp.getCmt().getCmtUrl().indexOf("?")>-1?"&":"?")+"&nodeid="+cp.getCmpId());
		m.put("icon", cp.getCmt().getCmtImg()==null||cp.getCmt().getCmtImg().equals("")?"workplace/image/icon/xitong.png":cp.getCmt().getCmtImg());
		List<CmsPage> childrenlist = getChildrenList(datalist, cp.getCmpId());
		if(childrenlist.isEmpty()){
			m.put("leaf", "true");
		}else{
			List<Map> nodelist = new ArrayList<Map>();
			for(int i=0;i<childrenlist.size();i++){
				CmsPage ccp = childrenlist.get(i);
				Map cm = getNodeList(ccp, datalist);
				nodelist.add(cm);
			}
			m.put("children", nodelist);
		}
		return m;
	}
	
	
	
	

}
